let http = require('../../utils/http.js');
var app = getApp();
var page = 1;
// var inputVal = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    songList: [],
    searchResult: [],
    inputVal: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: `点歌`
    })
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#FFFFFF',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  },

  /**
   * 返回
   */
  back: function () {
    wx.navigateTo({
      url: '../selectsongs/selectsongs',
    })
  },

  /**
   * 搜索函数
   */
  searchController: function (e) {
    this.setData({
      inputVal: e.detail.value
    })
    http.searchSong(this.data.inputVal, (result, data) => {
      let songList = [];
      let originSongs = data.body.song_list;
      for (var i = 0; i < originSongs.length; i++) {
        let bufferred = false
        let bufferredFilePath = null
        if (originSongs[i].id in app.globalData.bufferredSongs) {
          bufferred = true;
          bufferredFilePath = app.globalData.bufferredSongs[originSongs[i].id]["bufferredFilePath"];
        }
        songList.push({
          lrc: originSongs[i].lrc,
          name: originSongs[i].name,
          author: originSongs[i].author,
          link: originSongs[i].link,
          duration: originSongs[i].duration,
          id: originSongs[i].id,
          bufferred: bufferred,
          bufferredFilePath: bufferredFilePath,
        });
      }
      this.setData({
        songList: songList,
      })
    })
  },

  bufferSong: function(e) {
    /**
    * 本地显示处理
    */
    let hotSongs = this.data.hotSongs;
    var songid = parseInt(e.currentTarget.id);        //button传递歌曲id
    for (var i = 0; i < hotSongs.length; i++) {
      if (hotSongs[i]["id"] == songid) {
        console.log("------------------" + hotSongs[i]["bufferred"])
        if (hotSongs[i]["bufferred"]) {
          var newHistory = this.data.historySongs
          newHistory.push(hotSongs[i])
          this.setData({
            historySongs: newHistory
          })
          app.globalData.historySongs = this.data.historySongs;

          let pages = getCurrentPages();//当前页面
          let prevPage = pages[pages.length - 2];//上一页面
          prevPage.setData({//直接给上移页面赋值
            newSong: hotSongs[i],
          });

          wx.navigateBack({//返回
            delta: 1
          })
        } else {
          hotSongs[i]["bufferred"] = true;
          this.setData({ hotSongs: hotSongs })
          app.globalData.bufferredSongs[songid] = hotSongs[i];
        }
      }
    }
    console.log("bufferredSongs" + JSON.stringify(this.data.bufferredSongs))
  }

})